<?php
include 'Client.class.php';

set_time_limit(0);

header("Content-Type: text/html; charset=GBK");

class SmsClient {
	private static function loginBySetting($setting) {
		//	global $client;
		Log::write('Enter in sms');
		
		$gwUrl = 'http://sdkhttp.eucp.b2m.cn/sdk/SDKService?wsdl';
		//$serialNumber = '3SDK-BRB-0130-MEQPK';
		$serialNumber = $setting["msgSerialNumber"];
		//$password = '150832';
		$password = $setting["msgPwd"];
		$sessionKey = 'recbok';
		$connectTimeOut = 2;
		$readTimeOut = 10;
		$proxyhost = false;
		$proxyport = false;
		$proxyusername = false;
		$proxypassword = false;
		
		$client = new Client($gwUrl,$serialNumber,$password,$sessionKey,$proxyhost,$proxyport,$proxyusername,$proxypassword,$connectTimeOut,$readTimeOut);
		$client->setOutgoingEncoding("GBK");
		
		$statusCode = $client->login($sessionKey);
		if ($statusCode != null && $statusCode == "0") {
			return $client;
		} else {
			Log::write('sms login in error:' . $statusCode);
			return false;
		}
	}
	
	private static function login() {
		$customerId = Session::$user["customerId"];
		$setting = R('CUser/getSuperSettingById', array($customerId));
		if ($setting == NULL || empty($setting["msgSerialNumber"]) || empty($setting["msgPwd"])) {
			Output::instance()->resultCode(code_member_sms_no_point);
			return false;
		}
		// 		$setting["msgPointAvailable"] <= 0
		
		$result = self::loginBySetting($setting);
		if (!$result) {
			Output::instance()->resultCode(code_member_sms_api);
		}
		return $result;
	}
	
	public static function sendSMS($userName, $phone, $msg) {
		$client = self::login();
		if (!$client) {
			return false;
		}
		
		$msgPointAvailable = intval($client->getBalance() / $client->getEachFee());
		if ($msgPointAvailable <= 0) {
			Output::instance()->resultCode(code_member_sms_no_point);
			return false;
		}
		
		$sendMsg = iconv( 'UTF-8', 'GBK', $msg);
		$statusCode = $client->sendSMS(array($phone), $sendMsg);
// 		$client->logout();
		self::updateCustomerSuperSetting();
		self::writeLog($userName, $phone, $msg, true);
		Output::instance()->resultCode();
	}
	
	public static function getBalanceValue($setting) {
		$client = self::loginBySetting($setting, false);
		if (!$client) {
			return false;
		}
		
		$msgPointAvailable = intval($client->getBalance() / $client->getEachFee());
// 		$client->logout();
		return $msgPointAvailable;
	}
	
	public static function chargeUp($cardId, $cardPwd) {
		$client = self::login();
		if (!$client) {
			return false;
		}
		
		$statusCode = $client->chargeUp($cardId, $cardPwd);
		if ($statusCode !== null && $statusCode == 0) {
			$msgPointAvailable = intval($client->getBalance() / $client->getEachFee());
// 			$client->logout();
			$result["msgPointAvailable"] = $msgPointAvailable;
			Output::instance()->object($result);
			return true;
		}
		
		Log::write('sms charge up in error:' . $statusCode);
		Output::instance()->resultCode(code_member_sms_chargeup_failed, '充值失败，错误码' . $statusCode);
		return false;
	}
	
	private static function writeLog($userName, $phone, $msg, $isOk) {
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$SmsModel = M("sms_msg");
		$data["fromCustomerId"] = $customerId;
		$data["fromUserName"] = $userName;
		$data["phone"] = $phone;
		$data["content"] = $msg;
		$data["createTime"] = date("Y-m-d H:i:s");
		if ($isOk) {
			$data["point"] = 1;
		} else {
			$data["point"] = 0;
		}
		$SmsModel->add($data);
		
		Session::switchCustomer($customerId);
	}
	
	private static function updateCustomerSuperSetting() {
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$CustomerSuperSettingModel = D('customer_super_setting');
		$where["customerId"] = $customerId;
		// 余额通过接口获取，无需更新此处
		// $CustomerSuperSettingModel->where($where)->setDec('msgPointAvailable');
		$CustomerSuperSettingModel->where($where)->setInc('msgPointUsed');
		$CustomerSuperSettingModel->where($where)->setField('updateTime', date("Y-m-d H:i:s"));
		
		Session::switchCustomer($customerId);
	}
	
	private static function regist($client) {
		$eName = "epcloud";
		$linkMan = "fuwu";
		$phoneNum = "18901011111";
		$mobile = "18901011111";
		$email = "fuwu@happyidea.me";
		$fax = "18901011111";
		$address = "北京市朝阳区";
		$postcode = "100000";
		
		$statusCode = $client->registDetailInfo($eName,$linkMan,$phoneNum,$mobile,$email,$fax,$address,$postcode);
		if ($statusCode != null && $statusCode == "0") {
			Log::write('registDetailInfo in error:' . $statusCode);
		}
	}
}